import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { formatChatListTime } from '../../utils/dateFormat'

import './message.scss'
 

export default function Index() {
  const [items, setItems] = useState<any[]>([])

  useLoad(() => {
    fetchList()
  })
  useDidShow(() => {
    // 返回本页时刷新未读
    fetchList()
  })

  const fetchList = async () => {
    try {
      const app = Taro.getApp()
      // @ts-ignore
      const API_BASE = app?.globalData?.apiBase || Taro.getStorageSync('API_BASE') || 'http://localhost:3000'
      // @ts-ignore
      const currentUserId = app?.globalData?.currentUserId || Taro.getStorageSync('currentUserId')
      if (!currentUserId) {
        setItems([])
        Taro.showToast({ title: '未登录，无法加载会话', icon: 'none' })
        return
      }
      const [unreadRes, chatsRes] = await Promise.all([
        Taro.request({ url: `${API_BASE}/messages/unreadSummary`, method: 'GET', data: { userId: currentUserId } }),
        Taro.request({ url: `${API_BASE}/chats`, method: 'GET', data: { userId: currentUserId } })
      ])
      const unwrap = (res: any) => {
        const d = res?.data
        if (d?.data !== undefined) return d.data
        if (d?.result !== undefined) return d.result
        if (d?.list !== undefined) return d.list
        return d
      }
      const unreadRaw = unwrap(unreadRes)
      // 支持未读返回为对象或数组的两种格式
      const unreadMap: Record<string, { count: number, lastTime: number }> = Array.isArray(unreadRaw)
        ? unreadRaw.reduce((acc: Record<string, { count: number, lastTime: number }>, it: any) => {
            const id = String(it.userId || it.peerId || it._id || '')
            if (id) acc[id] = { count: Number(it.count || 0), lastTime: Number(it.lastTime || 0) }
            return acc
          }, {})
        : (unreadRaw || {})
      let chats: any[] = unwrap(chatsRes) as any[]
      if (!Array.isArray(chats) && chats && typeof chats === 'object') {
        // 兼容 { list: [...] } 或 { items: [...] }
        chats = (chats as any).list || (chats as any).items || []
      }
      const peerToLastTime: Record<string, number> = {}
      const peerToLastText: Record<string, string> = {}
      const peerToName: Record<string, string> = {}
      const peerToAvatar: Record<string, string> = {}
      chats.forEach((c) => {
        const other = (c.participants || []).find((p: any) => String(p._id || p) !== String(currentUserId))
        const otherId = String(other?._id || other)
        const last = (c.messages || []).slice(-1)[0]
        const t = last ? new Date(last.createdAt).getTime() : 0
        if (otherId) {
          peerToLastTime[otherId] = Math.max(peerToLastTime[otherId] || 0, t)
          if (last) peerToLastText[otherId] = last.content
          // 记录会话里携带的对端昵称和头像作为后备
          const name = other?.nickname || other?.name || other?.realName || other?.displayName || other?.username || ''
          const avatar = other?.avatar || other?.avatarUrl || ''
          if (name) peerToName[otherId] = name
          if (avatar) peerToAvatar[otherId] = avatar
        }
      })

      const ids = Array.from(new Set([...Object.keys(unreadMap), ...Object.keys(peerToLastTime)]))
      if (!ids.length) { setItems([]); return }
      
      console.log('获取用户信息，IDs:', ids)
      
      // 分别获取普通用户和医生信息
      const [usersRes, doctorsRes] = await Promise.all([
        Taro.request({ url: `${API_BASE}/users/byIds`, method: 'GET', data: { ids: ids.join(',') } }),
        Taro.request({ url: `${API_BASE}/cosmetic/doctors`, method: 'GET', data: { limit: 1000 } })
      ])
      
      console.log('用户信息API响应:', usersRes)
      console.log('医生信息API响应:', doctorsRes)
      
      // 处理普通用户数据
      let usersAny: any = unwrap(usersRes) || []
      let usersArr: any[] = []
      if (Array.isArray(usersAny)) {
        usersArr = usersAny
      } else if (usersAny && typeof usersAny === 'object') {
        if (Array.isArray(usersAny.list)) usersArr = usersAny.list
        else if (Array.isArray(usersAny.items)) usersArr = usersAny.items
        else usersArr = Object.values(usersAny)
      }
      
      // 处理医生数据
      let doctorsAny: any = unwrap(doctorsRes) || []
      let doctorsArr: any[] = []
      if (Array.isArray(doctorsAny)) {
        doctorsArr = doctorsAny
      } else if (doctorsAny && typeof doctorsAny === 'object') {
        if (Array.isArray(doctorsAny.data)) doctorsArr = doctorsAny.data
        else if (Array.isArray(doctorsAny.list)) doctorsArr = doctorsAny.list
        else if (Array.isArray(doctorsAny.items)) doctorsArr = doctorsAny.items
        else doctorsArr = Object.values(doctorsAny)
      }
      
      const userMap: Record<string, any> = {}
      usersArr.forEach((u) => { if (u && u._id) userMap[String(u._id)] = u })
      
      // 将医生数据也加入userMap，使用doctor_前缀作为ID
      doctorsArr.forEach((d) => { 
        if (d && d._id) {
          userMap[`doctor_${d._id}`] = {
            _id: `doctor_${d._id}`,
            nickname: d.name,
            username: d.name,
            name: d.name,
            avatar: d.avatar,
            hospital: d.hospital,
            specialties: d.specialties
          }
        }
      })
      const list = ids.map((id) => {
        // 尝试匹配医生ID（如果ID包含doctor_前缀）
        let u = userMap[id] || {}
        
        // 如果直接匹配不到，尝试匹配医生ID
        if (!u || Object.keys(u).length === 0) {
          // 检查是否是医生ID格式
          if (id.startsWith('doctor_')) {
            u = userMap[id] || {}
          } else {
            // 尝试在医生数据中查找匹配的ID
            const doctorKey = `doctor_${id}`
            u = userMap[doctorKey] || {}
          }
        }
        
        const displayName = u.nickname || u.username || u.name || u.realName || u.displayName || peerToName[id]
        const displayAvatar = u.avatar || u.avatarUrl || peerToAvatar[id] || ''
        
        // 添加调试日志
        console.log('用户信息调试:', {
          id,
          userData: u,
          displayName,
          peerToName: peerToName[id],
          finalName: displayName || `用户${id.slice(-4)}`,
          isDoctor: u.hospital ? true : false
        })
        
        return {
          _id: id,
          username: displayName || `用户${id.slice(-4)}`,
          avatar: displayAvatar || 'https://picsum.photos/80/80?random=' + id,
          count: unreadMap[id]?.count || 0,
          lastTime: Math.max(unreadMap[id]?.lastTime || 0, peerToLastTime[id] || 0),
          lastText: peerToLastText[id] || '',
          isDoctor: !!u.hospital,
          hospital: u.hospital || '',
          specialties: u.specialties || []
        }
      })
      // 未读优先，其次按最后时间倒序
      .sort((a, b) => {
        const aUnread = a.count > 0 ? 1 : 0
        const bUnread = b.count > 0 ? 1 : 0
        if (aUnread !== bUnread) return bUnread - aUnread
        return (b.lastTime || 0) - (a.lastTime || 0)
      })
      setItems(list)
    } catch (e: any) {
      const errMsg = e?.errMsg || e?.message || '未知错误'
      Taro.showToast({ title: `加载会话失败: ${errMsg}`.slice(0, 20), icon: 'none' })
      // 开发期可打印错误便于排查
      // eslint-disable-next-line no-console
      console.error('fetchList error', e)
    }
  }

  return (
    <View className='message-list'>
      <View className='message-header'>聊天列表</View>
      {items.map((it) => {
        // 处理最后一条消息的显示
        let lastMessageText = it.lastText || ''
        let messageClass = ''
        
        if (lastMessageText === '[图片]') {
          lastMessageText = '[图片]'
          messageClass = 'image-message'
        } else if (lastMessageText === '[语音消息]') {
          lastMessageText = '[语音]'
          messageClass = 'voice-message'
        }
        
        return (
          <View 
            key={it._id} 
            className={`message-item ${it.count > 0 ? 'has-unread' : ''}`}
            onClick={async () => {
              try {
                const app = Taro.getApp()
                // @ts-ignore
                const API_BASE = app?.globalData?.apiBase || Taro.getStorageSync('API_BASE') || 'http://localhost:3000'
                // @ts-ignore
                const currentUserId = app?.globalData?.currentUserId
                const open = await Taro.request({ url: `${API_BASE}/chats/open`, method: 'POST', data: { a: currentUserId, b: it._id } })
                const openData: any = open?.data?.data ?? open?.data
                const chatId = openData?._id
                if (chatId) {
                  // 先将该会话置为已读（当前用户），再跳转
                  await Taro.request({ url: `${API_BASE}/chats/${chatId}/readAll`, method: 'POST', data: { userId: currentUserId } })
                  // 本地乐观更新未读为 0
                  setItems((prev) => prev.map((x) => x._id === it._id ? { ...x, count: 0 } : x))
                  Taro.navigateTo({ url: `/pages/chat/chat?chatId=${chatId}&peerId=${it._id}` })
                }
              } catch (_) {}
            }}
          >
            <View className='message-avatar'>
              <Image 
                src={it.avatar} 
                mode='aspectFill'
                onError={() => {
                  console.log('头像加载失败:', it.avatar)
                }}
              />
            </View>
            <View className='message-content'>
              <View className='message-header-row'>
                <View className='message-username-container'>
                  <Text className='message-username'>{it.username}</Text>
                  {it.isDoctor && it.hospital && (
                    <Text className='message-doctor-info'> · {it.hospital}</Text>
                  )}
                </View>
                <Text className='message-time'>{it.lastTime ? formatChatListTime(it.lastTime) : ''}</Text>
              </View>
              {lastMessageText && (
                <Text className={`message-preview ${messageClass}`}>{lastMessageText}</Text>
              )}
            </View>
            {it.count > 0 && (
              <Text className='message-unread'>{it.count}</Text>
            )}
          </View>
        )
      })}
      {items.length === 0 && (
        <View className='message-empty'>暂无会话</View>
      )}
    </View>
  )
}

